package io.ukoko.controller;

import io.ukoko.dto.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
public class FileController
{
    /**
     * 文件上传
     */
    @PostMapping(value = "/uploadFile")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        // 获取文件格式
        String Sub = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
//        System.out.println(Sub);

        // 重新命名
        String newFileName = UUID.randomUUID().toString();
        // 新文件名
        fileName = newFileName + Sub;
//        System.out.println(fileName);

        // 获取项目运行的真实地址
        String realPath = request.getServletContext().getRealPath("/pic");
        File f = new File(realPath);
        if (!f.exists())
        {
            f.mkdirs();
        }
//        System.out.println("真实地址" + f);
        // 将图片保存到此地址
        file.transferTo(new File(f + "/" + fileName));

        // 服务器地址
        String bookUrl = "/pic/" + fileName;
        // 本地真实地址
        String bookAddress = f + "/" + fileName;

        Map<String, String> map = new HashMap<>();
        map.put("bookUrl", bookUrl);
        map.put("bookAddress", bookAddress);

        return Result.ok(map);
    }
}
